//使用数组实现一个阻塞队列 - 环形队列
public class MyBlockingQueue {
    private String[] data = new String[1000];
    private int size = 0;
    private int head = 0;
    private int tail = 0;//指向最后一个元素的下一个位置
    synchronized public void put(String s) throws InterruptedException { //同一时刻，只能有1个线程放入元素和取出元素
        //放入元素之前，要先判断队列满不满
        while(size == data.length){//使用while的原因： 防止wait被interrupt()方法解除阻塞
            //满了要阻塞等待，等待其他线程取出元素
            this.wait();
        }
        data[tail] = s;
        tail = (tail + 1) % data.length;
        size++;
        this.notify();
    }
    synchronized public String take() throws InterruptedException {
        //取出元素之前，要判断队列空不空
        while(size == 0){//使用while的原因： 防止wait被interrupt()方法解除阻塞
            //队列是空的要阻塞等待，等待其它线程放入元素
            this.wait();
        }
        String ret = data[head];
        head = (head + 1) % data.length;
        size--;
        this.notify();
        return ret;
    }
}

class Test{
    public static void main(String[] args) {
        MyBlockingQueue myBlockingQueue = new MyBlockingQueue();
        Thread t1 = new Thread(() -> {
            //生产者
            int count = 1;
            while(true){
                try {
                    myBlockingQueue.put(count + "");
                    System.out.println("生产数据：" + count);
                    Thread.sleep(500);
                    count++;
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        Thread t2 = new Thread(() -> {
            //消费者
            while(true){
                try {
                    String ret = myBlockingQueue.take();
                    System.out.println("消费数据：" + ret);

                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        t1.start();
        t2.start();
    }
}
